<template>
    <div>
<!--      面包屑导航-->
<!--      <el-breadcrumb separator-class="el-icon-arrow-right">-->
<!--        <el-breadcrumb-item :to="{ path: '/users' }">首页</el-breadcrumb-item>-->
<!--        <el-breadcrumb-item>用户管理</el-breadcrumb-item>-->
<!--        <el-breadcrumb-item>用户列表</el-breadcrumb-item>-->
<!--      </el-breadcrumb>-->
<!--      卡片视图区域-->
      <bread-list :navData="navData"></bread-list>
      <el-card class="box-card">
<!--         搜索与添加区域-->
        <el-row :gutter="20">
          <el-col :span="7">
            <el-input placeholder="请输入内容" v-model="query" class="input-with-select" clearable @clear="getUserList">
              <el-button slot="append" icon="el-icon-search" @click="searchUser"></el-button>
            </el-input>
          </el-col>
         <el-col :span="4">
           <el-button type="primary" @click="openAddUserDialog">添加用户</el-button>
         </el-col>
        </el-row>
<!--        用户列表区域-->
        <el-table height="480" :data="userList" :border="true" :stripe="true">
          <el-table-column align="center" label="#" type="index"></el-table-column>
          <el-table-column align="center" label="姓名" prop="username"></el-table-column>
          <el-table-column align="center" label="邮箱" prop="email"></el-table-column>
          <el-table-column align="center" label="电话" prop="mobile"></el-table-column>
          <el-table-column align="center" label="角色" prop="role_name"></el-table-column>
          <el-table-column align="center" label="状态" >
<!--            作用域插槽-->
            <template slot-scope="scope">
              <el-switch v-model="scope.row.mg_state" @change="userStatusChange(scope.row)">

              </el-switch>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" >
            <template slot-scope="scope">
<!--              修改用户按钮-->
              <el-button type="primary" icon="el-icon-edit" size="mini" @click="openEditUserDialog(scope.row)"></el-button>
<!--              删除用户按钮-->
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteUser(scope.row.id)"></el-button>
<!--              分配角色按钮-->
              <el-tooltip :enterable="false" class="item" effect="dark" content="分配角色" placement="bottom-start">
                <el-button type="warning" icon="el-icon-setting" size="mini" @click="setUserRole(scope.row)"></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
<!--        分页区域-->
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pagenum"
            :page-sizes="[10, 20, 40, 50]"
            :page-size="pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
        </el-pagination>
      </el-card>
<!--      // 添加用户对话框-->
      <el-dialog
          title="添加用户"
          :visible.sync="addUserDialogVisible"
          width="20%"
          @close="addUserDialogClose"
          >
<!--        内容主体区-->
        <el-form :model="addUserForm" :rules="addUserFormRules" ref="addUserRefForm" label-width="70px" status-icon >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addUserForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addUserForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addUserForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="addUserForm.mobile"></el-input>
          </el-form-item>
        </el-form>
<!--        对话框底部区域-->
        <span slot="footer" class="dialog-footer">
        <el-button @click="addUserDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
  </span>
      </el-dialog>
<!--        修改用户对话框-->
      <el-dialog
          title="修改用户"
          :visible.sync="editUserDialogVisible"
          width="20%"

      >
        <!--        内容主体区-->
        <el-form :model="editUserForm" :rules="addUserFormRules" ref="editUserRefForm" label-width="70px" status-icon >
          <el-form-item label="用户名" prop="username">
            <el-input disabled v-model="editUserForm.username"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" >
            <el-input v-model="editUserForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" >
            <el-input v-model="editUserForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <!--        对话框底部区域-->
        <span slot="footer" class="dialog-footer">
        <el-button @click="editUserDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="editUser()">确定</el-button>
  </span>
      </el-dialog>
<!--      设置用户角色对话框-->
      <el-dialog title="分配角色" :visible.sync="setRoleDialogVisible" width="30%" >
        <p>当面用户名：{{ userInfo.username }}</p>
        <p>当前用户角色：{{ userInfo.role_name}}</p>
        <p>分配新角色：
          <el-select v-model="selectedRole" placeholder="请选择">
            <el-option
                v-for="item in roleList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id">
            </el-option>
          </el-select>
        </p>
        <!--        对话框底部区域-->
        <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="setRole()">确定</el-button>
      </span>
      </el-dialog>
    </div>
</template>

<script>
import BreadList from "../common/BreadList";
export default {
  name: "User",
  components:{
    BreadList
  },
  data(){
    return{
      navData:{
        navNameFir:'用户管理',
        navSecond:'用户列表',
        path:'/home'
      },
      userInfo:{}, //设置角色的当前用户信息
      query:'',//查询参数
      pagenum:1,// 当前页码
      pagesize:10,// 每页显示条数
      userList:[], //管理员列表数据
      total:0 ,// 列表总数
      userId:'',//用户id
      addUserDialogVisible:false, //添加用户对话框默认显示
      editUserDialogVisible:false, //修改用户对话框默认显示
      addUserForm:{
        username:'',
        password:'',
        email:'',
        mobile:''
      }, // 添加用户的数据源
      editUserForm:{
        username:'',
        email:'',
        mobile:''
      },// 修改用户的数据源
      selectedRole:'', //当前选择的角色
      setRoleDialogVisible:false, //设置用户角色对话框
      roleList:[], //角色列表
      addUserFormRules:{ // 表单的验证规则
        username:[
          { required:true, message:'请输入用户名',trigger:'blur'},
          { min: 3, max: 10, message: '用户名的长度在3-10之间'}
        ],
        password:[
          { required:true, message:'请输入密码',trigger:'blur'},
          { min: 6, max: 15, message: '用户名的长度在6-15之间'}
        ],
        email:[
          { required:true, message:'请输入邮箱',trigger:'blur'},
          { pattern: /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/, message: '请输入正确的邮箱'}

        ],
        mobile:[
          { required:true, message:'请输入手机号',trigger:'blur'},
          { pattern: /^1[3|5|7|8|9]\d{9}$/,message:'请输入正确的手机号',trigger: 'blur'}
        ]
      }
    }
  },
  mounted() {
    this.getUserList()
  },
  methods:{
    // 搜索用户
    searchUser(){
      this.getUserList()
    },
    // 点击添加用户按钮，打开弹窗
    openAddUserDialog(){
      this.addUserDialogVisible = true

    },
    // 打开用户修改按钮，打开对话框
    openEditUserDialog(userInfo){
      this.editUserDialogVisible = true
      this.editUserForm.username = userInfo.username
      this.editUserForm.email = userInfo.email
      this.editUserForm.mobile = userInfo.mobile
      this.userId = userInfo.id
    },
    // editUserDialogClose(){  // 关闭对话框  重置数据、
    //   this.$refs.editUserRefForm.resetFields()
    //   this.getUserList()
    // },
    // 获取用户列表数据
    async getUserList(){
      const params = {
        query:this.query,
        pagenum:this.pagenum,
        pagesize:this.pagesize
      }
      const {data:res} = await this.$http.get('users',{params:params})
      console.log(res);
      const { data, meta }  =  res
      if(meta.status === 200){
        this.$message.success(meta.msg,2000)
        this.userList = data.users
        this.total = data.total
      }else {
        this.$message.error(meta.msg)
      }
    },
    // 监听pagesize改变的事件
    handleSizeChange(newSize){
      console.log(newSize);
      this.pagesize = newSize
      this.getUserList()
    },
    // 监听当前页码（pagenum）改变的事件
    handleCurrentChange(newPage){
      console.log(newPage);
      this.pagenum = newPage
      this.getUserList()
    },
    // 修改用户状态接口调用
    async changeUserStatus(userInfo){
      const { data: res } = await  this.$http.put("users/" + Number(userInfo.id) + "/state/" + userInfo.mg_state)
      if(res.meta.status === 200){
        this.$message.success(res.meta.msg,2000)
      }else {
        userInfo.mg_state = !userInfo.mg_state
        this.$message.error(res.meta.msg)
      }
    },
    // 监听用户状态按钮改变的事件
    userStatusChange(userInfo){
      // console.log(userInfo);
      this.changeUserStatus(userInfo)
    },
    // 关闭对话框触发的方法
    addUserDialogClose(){
      this.$refs.addUserRefForm.resetFields()
    },
    // 点击按钮，添加用户
    addUser(){
      this.$refs.addUserRefForm.validate( async valid =>{
        if(valid){
          // 可以发起添加用户的网络请求
          const { data:res } = await this.$http.post('users',this.addUserForm)
          const {meta:meta} = res
          console.log(res);
          meta.status === 201 ? this.$message.success(meta.msg) : this.$message.error(meta.msg)
          this.addUserDialogVisible = false
          await this.getUserList()
        }else {
          return
        }

      })
    },
    editUser(){
      this.$refs.editUserRefForm.validate( async valid =>{
        if(valid){
          const { data:res }  = await this.$http.put('users/' + this.userId,this.editUserForm )
          const { meta: meta } = res
          if(meta.status === 200){
            this.$message.success(meta.msg)
            this.editUserDialogVisible = false
            await this.getUserList()
          }else {
            this.$message.success(meta.msg)
            this.editUserDialogVisible = false
          }
        }else {
          return
        }
      })
    },
    // 删除用户
    async deleteUser(id){
      const confirm = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if(confirm === 'confirm'){
        // 调用删除用的接口
        const  { data:res } = await this.$http.delete('users/' + id)
        res.meta.status === 200 ? this.$message.success(res.meta.msg) : this.$message.error(res.meta.msg)
        await this.getUserList()
        // console.log(res)
        // console.log(confirm);
        console.log(confirm)
      }else {
        this.$message.info('已取消删除')
      }
      // console.log(confirm);
    },
    // 给用户设置角色
    setUserRole(userInfo){
      this.userInfo = userInfo
      this.setRoleDialogVisible = true
      this.getRoleList()

    },
    // 获取用户角色列表
    async getRoleList(){
      const { data:res } = await this.$http.get('roles')
      if(res.meta.status === 200){
        this.roleList = res.data
      }else {
        this.$message.error(res.meta.msg)
      }
      console.log(res);
    },
    // 点击确定，设置角色
    async setRole(){
      const  { data:res }  = await this.$http.put('users/' + this.userInfo.id + '/role',{rid:this.selectedRole})
      const { meta:meta } = res
      // console.log(res);
      if(meta.status === 200){
        await this.getUserList()
        this.setRoleDialogVisible = false
        this.selectedRole = ''
        this.$message.success(meta.msg)
      }else {
        this.$message.error(meta.msg)
      }
    }

  }
}
</script>

<style scoped lang="less">

</style>